import 'dart:math';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:qlevar_router/qlevar_router.dart';
import 'package:stacked/stacked.dart';
import '../../heartbeat/helpers/magma_constant.dart';
import '../../heartbeat/helpers/magma_text_style.dart';
import '../../heartbeat/helpers/magma_color.dart';
import '../../heartbeat/parts/magma_report_dialog.dart';
import '../../heartbeat/helpers/magma_toast.dart';

/// AI助手消息模型
class AiMessageModel {
  final String content;
  final bool isUser;
  final DateTime timestamp;

  AiMessageModel({
    required this.content,
    required this.isUser,
    required this.timestamp,
  });
}

/// AI助手响应模型
class AiResponseModel {
  final String answer;
  final String conversationId;
  final int showSec;

  AiResponseModel({
    required this.answer,
    required this.conversationId,
    required this.showSec,
  });

  factory AiResponseModel.fromJson(Map<String, dynamic> json) {
    return AiResponseModel(
      answer: json['answer'] ?? '',
      conversationId: json['conversation_id'] ?? '',
      showSec: json['show_sec'] ?? 0,
    );
  }
}

/// AI助手视图模型
class AiHelperNavigatorViewModel extends BaseViewModel {
  final Dio _dio = Dio();
  final TextEditingController _messageController = TextEditingController();

  List<AiMessageModel> _messages = [];
  String? _conversationId;
  String? _sessionId;
  bool _isLoading = false;

  List<AiMessageModel> get messages => _messages;
  TextEditingController get messageController => _messageController;
  bool get isLoading => _isLoading;

  /// 初始化AI助手
  void initializeAiHelper() {
    _sessionId = _generateSessionId();
    _addWelcomeMessage();
  }

  /// 生成会话ID
  String _generateSessionId() {
    final now = DateTime.now();
    final timestamp =
        '${now.year}${now.month.toString().padLeft(2, '0')}${now.day.toString().padLeft(2, '0')}';
    final randomString = _generateRandomString(16);
    return '${timestamp}_$randomString';
  }

  /// 生成随机字符串
  String _generateRandomString(int length) {
    const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
    final random = Random();
    return String.fromCharCodes(
      Iterable.generate(
        length,
        (_) => chars.codeUnitAt(random.nextInt(chars.length)),
      ),
    );
  }

  /// 添加欢迎消息
  void _addWelcomeMessage() {
    _messages.add(
      AiMessageModel(
        content: "Hello, how can I help you?",
        isUser: false,
        timestamp: DateTime.now(),
      ),
    );
    notifyListeners();
  }

  /// 发送消息
  Future<void> sendMessage() async {
    final message = _messageController.text.trim();
    if (message.isEmpty) return;

    // 添加用户消息
    _messages.add(
      AiMessageModel(content: message, isUser: true, timestamp: DateTime.now()),
    );

    _messageController.clear();
    _isLoading = true;
    notifyListeners();

    try {
      final response = await _sendToAi(message);
      if (response != null && response.answer.isNotEmpty) {
        // 添加AI回复
        _messages.add(
          AiMessageModel(
            content: response.answer,
            isUser: false,
            timestamp: DateTime.now(),
          ),
        );
        _conversationId = response.conversationId;
      }
    } catch (e) {
      // 添加错误消息
      _messages.add(
        AiMessageModel(
          content: "Sorry, I'm having trouble connecting. Please try again.",
          isUser: false,
          timestamp: DateTime.now(),
        ),
      );
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  /// 发送消息到AI接口
  Future<AiResponseModel?> _sendToAi(String message) async {
    try {
      final requestData = {
        'bundle_id': 'com.magma.app',
        'session_id': _sessionId,
        'content_type': 'text',
        'content': message,
      };

      // 如果有会话ID，添加到请求中
      if (_conversationId != null) {
        requestData['conversation_id'] = _conversationId;
      }

      final response = await _dio.post(
        'https://api.wiseaii.com/wiseai/v1/chat',
        data: requestData,
        options: Options(headers: {'Content-Type': 'application/json'}),
      );

      if (response.statusCode == 200) {
        final data = response.data;
        if (data['code'] == 1003) {
          return AiResponseModel.fromJson(data['data']);
        }
      }
      return null;
    } catch (e) {
      print('AI API Error: $e');
      return null;
    }
  }

  @override
  void dispose() {
    _messageController.dispose();
    super.dispose();
  }
}

/// AI助手页面
class AiHelperStory extends StatelessWidget {
  const AiHelperStory({super.key});

  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<AiHelperNavigatorViewModel>.reactive(
      viewModelBuilder: () => AiHelperNavigatorViewModel(),
      onModelReady: (vm) => vm.initializeAiHelper(),
      builder: (context, viewModel, child) {
        return Scaffold(
          backgroundColor: MagmaColor.black,
          body: SafeArea(
            bottom: false,
            child: Column(
              children: [
                // 顶部导航栏
                _constructNavigationBar(context),
                // 聊天内容区域
                Expanded(child: _buildChatContent(viewModel)),
                // 底部输入区域
                _buildInputArea(viewModel),
              ],
            ),
          ),
        );
      },
    );
  }

  /// 构建导航栏
  Widget _constructNavigationBar(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
      child: Row(
        children: [
          GestureDetector(
            onTap: () => QR.back(),
            child: Image.asset(MagmaConstant.back, width: 20.w, height: 25.w),
          ),
          Spacer(),
          Text(
            'AI Assistant',
          ).blackHanSans(fontSize: 24.sp, color: MagmaColor.white),
          Spacer(),
          GestureDetector(
            onTap: () => _showReportDialog(context),
            child: Image.asset(MagmaConstant.report, width: 25.w, height: 25.w),
          ),
        ],
      ),
    );
  }

  /// 构建聊天内容区域
  Widget _buildChatContent(AiHelperNavigatorViewModel viewModel) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Column(
        children: [
          // 介绍文本
          Container(
            padding: EdgeInsets.symmetric(vertical: 20.h),
            child: Column(
              children: [
                Text(
                  'Marathon AI Assistant is not only your running tool, but also your guide to surpass yourself.',
                  textAlign: TextAlign.center,
                ).blackHanSans(
                  fontSize: 16.sp,
                  color: MagmaColor.white,
                  fontWeight: FontWeight.w400,
                ),
                SizedBox(height: 16.h),
                Container(
                  height: 1.h,
                  decoration: BoxDecoration(
                    border: Border(
                      top: BorderSide(
                        color: MagmaColor.white.withValues(alpha: 0.3),
                        width: 1.w,
                        style: BorderStyle.solid,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
          // 消息列表
          Expanded(
            child: ListView.builder(
              itemCount: viewModel.messages.length,
              itemBuilder: (context, index) {
                final message = viewModel.messages[index];
                return _buildMessageBubble(message, index);
              },
            ),
          ),
        ],
      ),
    );
  }

  /// 构建消息气泡
  Widget _buildMessageBubble(AiMessageModel message, int index) {
    return Container(
      margin: EdgeInsets.only(bottom: 16.h),
      child: Row(
        mainAxisAlignment:
            message.isUser ? MainAxisAlignment.end : MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (!message.isUser) ...[
            // AI方没有头像
            SizedBox.shrink(),
          ],
          Flexible(
            flex: message.isUser ? 3 : 4, // 用户方占用更多空间
            child: Container(
              constraints: BoxConstraints(
                minHeight: 42.w, // 最小高度与头像一致
                maxWidth: 280.w, // 最大宽度限制
              ),
              padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
              decoration: BoxDecoration(
                color: message.isUser ? MagmaColor.grey : MagmaColor.green,
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(message.isUser ? 16.r : 0.r),
                  topRight: Radius.circular(message.isUser ? 0.r : 16.r),
                  bottomLeft: Radius.circular(16.r),
                  bottomRight: Radius.circular(16.r),
                ),
              ),
              child: Text(
                message.content,
                style: TextStyle(
                  color: message.isUser ? MagmaColor.white : MagmaColor.black,
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w400,
                ),
              ),
            ),
          ),
          if (message.isUser) ...[
            SizedBox(width: 8.w),
            Container(
              width: 42.w,
              height: 42.w,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                image: DecorationImage(
                  image: AssetImage(MagmaConstant.avatar2),
                  fit: BoxFit.cover,
                ),
              ),
            ),
          ] else ...[
            SizedBox(width: 16.w), // AI方右边距
          ],
        ],
      ),
    );
  }

  /// 构建输入区域
  Widget _buildInputArea(AiHelperNavigatorViewModel viewModel) {
    return Stack(
      clipBehavior: Clip.none,
      children: [
        Positioned(
          top: -26.h,
          left: 0,
          right: 0,
          child: Image.asset(
            MagmaConstant.decoration,
            width: double.infinity,

            fit: BoxFit.fitWidth,
          ),
        ),
        // 输入框容器
        Container(
          padding: EdgeInsets.only(
            left: 16.w,
            right: 16.w,
            top: 16.h,
            bottom: 44.h,
          ),
          decoration: BoxDecoration(
            color: MagmaColor.black,
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(20.r),
              topRight: Radius.circular(20.r),
            ),
          ),
          child: Container(
            height: 56.h,
            decoration: BoxDecoration(
              color: MagmaColor.white,
              borderRadius: BorderRadius.circular(12.r),
            ),
            child: Row(
              children: [
                Expanded(
                  child: Padding(
                    padding: EdgeInsets.symmetric(horizontal: 16.w),
                    child: TextField(
                      controller: viewModel.messageController,
                      decoration: InputDecoration(
                        hintText: 'Say Something...',
                        hintStyle: TextStyle(
                          color: MagmaColor.grey,
                          fontSize: 14.sp,
                        ),
                        border: InputBorder.none,
                      ),
                      style: TextStyle(
                        color: MagmaColor.black,
                        fontSize: 14.sp,
                      ),
                      onSubmitted: (_) => viewModel.sendMessage(),
                    ),
                  ),
                ),
                GestureDetector(
                  onTap: viewModel.isLoading ? null : viewModel.sendMessage,
                  child: Container(
                    margin: EdgeInsets.only(right: 8.w),
                    padding: EdgeInsets.symmetric(horizontal: 16.w),
                    height: 40.h,
                    decoration: BoxDecoration(
                      color:
                          viewModel.isLoading
                              ? MagmaColor.grey.withValues(alpha: 0.5)
                              : MagmaColor.purple,
                      borderRadius: BorderRadius.circular(12.r),
                    ),
                    child: Center(
                      child:
                          viewModel.isLoading
                              ? SizedBox(
                                width: 16.w,
                                height: 16.w,
                                child: CircularProgressIndicator(
                                  strokeWidth: 2.w,
                                  valueColor: AlwaysStoppedAnimation<Color>(
                                    MagmaColor.white,
                                  ),
                                ),
                              )
                              : Text('Send', style: TextStyle()).blackHanSans(
                                color: MagmaColor.black,
                                fontSize: 18.sp,
                                fontWeight: FontWeight.w400,
                              ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  /// 显示举报对话框
  void _showReportDialog(BuildContext context) {
    MagmaReportDialog.showReportDialog(
      context,
      title: 'Report AI Assistant',
      subtitle: 'Please select the reason for reporting this AI assistant.',
      onReportSubmitted: (ReportOption option) {
        // 显示举报成功提示
        MagmaToast.success(
          context,
          title: 'Report Submitted',
          description: 'Thank you for helping us maintain a safe community.',
        );
        // 延迟返回上一个页面
        Future.delayed(const Duration(milliseconds: 1500), () {
          QR.back();
        });
      },
    );
  }
}
